// 和用户相关的状态管理
import {createSlice} from "@reduxjs/toolkit";
import {getToken, removeToken, setToken as _setToken} from "@/utils";
import {getProfileAPI, LoginAPI} from "@/apis/user";

const userStore = createSlice({
    name: "user",
    // 数据状态
    initialState: {
        token: getToken() || '',
        userInfo: {}
    },
    // 同步修改方法
    reducers: {
        setToken(state, action) {
            // 存入到redux
            state.token = action.payload
            // 存入到localstorage，token持久化
            _setToken(action.payload)
        },
        setUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearUserInfo(state) {
            state.token = ''
            state.userInfo = []
            removeToken()
        },
    }
});

// 异步方法
// 完成登录获取token
const fetchLogin = (loginForm) => {
    return async (dispatch) => {
        // 发起异步请求
        const res = await LoginAPI(loginForm);
        // 提交同步action进行token存入
        dispatch(setToken(res.data.token))
    }
}

// 获取用户数据
const fetchUserInfo = () => {
    return async (dispatch) => {
        // 发起异步请求
        const res = await getProfileAPI();
        // 提交同步action进行token存入
        dispatch(setUserInfo(res.data))
    }
}

// 解构actions
const {setToken, setUserInfo, clearUserInfo} = userStore.actions;

// 解构reducer
const reducer = userStore.reducer;

// 导出
export {fetchLogin, setToken, fetchUserInfo, clearUserInfo}
export default reducer